import api from '@/api';
import i18n from '@/locales';
import { ElLoading } from 'element-plus';

export default {
    state: {
        base: {},
        storage: {},
		//移动端布局
		ismobile: false,
    },
    mutations: {
        SET_CONFIG(state, key) {
            state.base = key;
            // 更新 i18n 语言环境
            i18n.global.locale = key.app_lang;
        },
		SET_ISMOBILE(state, key){
			state.ismobile = key;
		},
        SET_LANG(state, lang) {
            state.base.app_lang = lang;
            // 更新 i18n 语言环境
            i18n.global.locale = lang;
        },
        SET_DARK_MODE(state, dark) {
            state.base.app_dark = dark;
        },
        SET_LAYOUT(state, key) {
			state.base.layout = key;
		},
		SET_MENU_IS_COLLAPSE(state) {
			state.base.menu_is_collapse = state.base.menu_is_collapse === '0' ? '1' : '0';
		},
        SET_LAYOUT_TAGS(state) {
			state.base.layout_tags = state.base.layout_tags === '0' ? '1' : '0';
        },
        SET_STORAGE(state, key) {
            state.storage = key;
        },
    },
    actions: {
        async GET_CONFIG({ commit }, type) {
            try {
                const config = await api.setting.system.list.get({ type })
                if (config.code == 200) 
                {
                    if (type == 'base') {
                        commit("SET_CONFIG", config.data.base);
                        i18n.global.locale = config.data.base.app_lang;
                    } else if (type == 'storage') {
                        commit("SET_STORAGE", config.data.storage);
                    }
                }
            } catch (error) {
                console.error('Error in GET_CONFIG action:', error);
            }
        },
        async SET_LANG({ commit }, lang) {
            try {
                const res = await api.setting.system.lang.post({ value:lang })
                if (res.code === 200) {
                    const loading = ElLoading.service({
                        lock: true,
                        text: i18n.global.t('login.changeLang'),
                        background: 'rgba(0, 0, 0, 0.7)',
                    });
                    setTimeout(() => {
                        loading.close();
                        commit('SET_LANG', lang);
                    }, 3000);
                }
            } catch (error) {
                console.error('Error in SET_LANG action:', error);
            }
        },
        SET_DARK_MODE({ commit, state }) {
            commit('SET_DARK_MODE', state.base.app_dark === '0' ? '1' : '0');
        },
    }
}